﻿//2009-12-14    登入頁面初始    By Victor
//2010-03-02    修改使用者登入Log及判斷是否為系統管理者     By Victor
//2010-06-01    修改從iEN-Adv單一登入功能，帶入身分到Session中，並且多帶入一個Session["AdvUser"]，並直接導入相對應的案場即時狀態      By Lights
//2010-06-03    修改從iEN-Adv單一登入功能，多帶入一個Session["AdvSiteID"]      By Lights
//2010-09-09    修正A站iframe引用其它站(B站)的內容時，B站的頁面獲取不到B站種下的Cookies。 By May
//              如果頁面是來自框架(frame)的，而框架的父頁和框架不是一個站點的話，客戶端默認是禁止向頁面附加頭信息的，
//              這樣服務器端就無法識別客戶端框架裡面的頁面，自然不能操作Session / Cookie。
//              修正方式：在Page_Load加入HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR");
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using DataAccess;

namespace iEN
{
    public partial class Login : System.Web.UI.Page
    {
        private string strDSN = System.Configuration.ConfigurationManager.AppSettings["strDSN"];

        #region protected void Page_Load(object sender, EventArgs e)        //頁面初始，判斷是否從Advanced上導覽過來
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("P3P", "CP=CAO PSA OUR");
            if (!this.Page.IsPostBack)
                this.LoginFromAdv();
        }

        private void LoginFromAdv()
        {
            string par = this.Page.Request.QueryString["par"];
            if (string.IsNullOrEmpty(par))
                return;
            iEN_AdvAPI.Encode.Credential cred = iEN_AdvAPI.Encode.EncoderAccessory.GetCredential(par);
            //帶入身分
            if (cred.Account.Length == 0)
                return;
            this.Page.Session["LoginID"] = cred.Account;                                                                  //使用者ID
            this.Page.Session["LoginName"] = string.Format("Adv_User: {0}, Level: {1}", cred.Account, cred.Level);        //使用姓名
            this.Page.Session["SysAdmin"] = "0";                                                                          //記錄是否為平台管理者
            this.Page.Session["LoginIP"] = this.Page.Request.ServerVariables["Remote_Addr"];                              //登入IP
            this.Page.Session["AliveTime"] = DateTime.Now;                                                                //判斷使用者最後操作時間
            this.Page.Session["AdvUser"] = true;                                                                          //記錄是否為Advanced登入的使用者
            this.Page.Session["AdvSiteID"] = cred.SiteID;                                                                 //紀錄從Advanced得到的SiteID資訊
            //導入即時狀態頁面
            string encryptedSiteID = new iEN_AdvAPI.Encode.Coder().Encode(cred.SiteID);
            this.Page.Response.Redirect(string.Format(@"Immediate\ShowNow.aspx?SiteID={0}", encryptedSiteID));
        }
        #endregion

        #region protected void btnLogin_Click(object sender, EventArgs e)       //按下『登入』按鈕
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string strUserID = tbID.Text.Trim();
            string strPW = tbPW.Text.Trim();

            if (strUserID == "" || strPW == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('帳號密碼不得為空！')", true);
                return;
            }

            string strLoginIP = Request.ServerVariables["Remote_Addr"];

            /*
            Session["LoginID"] = strUserID;            //使用者ID
            Session["LoginName"] = strUserID;        //使用姓名
            Session["SysAdmin"] = "1";        //記錄是否為平台管理者
            Session["LoginIP"] = strLoginIP;                                    //登入IP
            Session["AliveTime"] = DateTime.Now;                                //判斷使用者最後操作時間
            Response.Redirect(@"Immediate\ShowNow.aspx");
             */

            ///////////////////////////////
            DataTable dtTemp = new DBAccess().getUserData("1");
            int i;

            for (i = 0; dtTemp != null && i < dtTemp.Rows.Count; i++)
                if (dtTemp.Rows[i]["_account"].ToString() == strUserID && dtTemp.Rows[i]["_password"].ToString() == strPW && 
                    dtTemp.Rows[i]["_enable"].ToString()=="True")
                    break;

            if (dtTemp != null && i<dtTemp.Rows.Count)
            {
                Session["LoginAccount"] = strUserID;
                Session["LoginName"] = dtTemp.Rows[i]["_name"].ToString();
                Session["SysAdmin"] = dtTemp.Rows[i]["_type"].ToString();
                Session["LoginIP"] = strLoginIP;
                Session["AliveTime"] = DateTime.Now;

                new DBAccess().addEventLog(strUserID, strLoginIP, 1, "", "1");

                // Response.Redirect(@"Immediate\ShowNow.aspx");
                this.Page.Response.Redirect("Immediate\\ShowNow.aspx");
            }
            else
            {
                new DBAccess().addEventLog(strUserID, strLoginIP, 1, "", "0");

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('登入失敗，請重新確認帳號密碼是否正確！')", true);
                return;
            }

            //DataTable dtTemp = new UserSet().UserAuth(strUserID, strPW);
            //if (dtTemp!= null && dtTemp.Rows .Count >0)
            //{
            //    string strLock = dtTemp.Rows[0]["Locked"].ToString();
            //    string strDueDate = dtTemp.Rows[0]["DueDate"].ToString();
            //    if (strLock == "1")
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('該帳號已被鎖定無法登入，請聯絡系統管理員！')", true);
            //        return;
            //    }
            //    else if (strDueDate!= "" && DateTime .Compare (DateTime .Now, Convert.ToDateTime (strDueDate)) >= 0)
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('該帳號已過期無法登入，請聯絡系統管理員！')", true);
            //        return;
            //    }
            //    else
            //    {
            //        string strLoginIP = Request.ServerVariables["Remote_Addr"];         //登入IP                      
            //        new UserSet().AddSysLog("平台", strUserID, strLoginIP, UserSet.eEventType.登入成功.ToString(), "使用者登入成功。");

            //        Session["LoginID"] = dtTemp.Rows[0]["UserID"].ToString();            //使用者ID
            //        Session["LoginName"] = dtTemp.Rows[0]["UserName"].ToString();        //使用姓名
            //        Session["SysAdmin"] = dtTemp.Rows[0]["SysAdmin"].ToString();        //記錄是否為平台管理者
            //        Session["LoginIP"] = strLoginIP;                                    //登入IP
            //        Session["AliveTime"] = DateTime.Now;                                //判斷使用者最後操作時間
            //        Response.Redirect(@"Immediate\ShowNow.aspx");  

            //    }
            //}
            //else
            //{
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('登入失敗，請重新確認帳號密碼是否正確！')", true);
            //        return;
            //}
        }
        #endregion

        #region protected void btnClear_Click(object sender, EventArgs e)       //按下『清除』按鈕
        protected void btnClear_Click(object sender, EventArgs e)
        {
            tbID.Text = "";
            tbPW.Text = "";
        }
        #endregion

    }
}
